package tech.cn.note.html;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import tech.cn.note.html.tool.DocumentConfiguration;
import tech.cn.note.html.tool.DocumentConvert;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * 使用freemarker进行模板数据转换
 * 1.可根据XML或HTML模板进行数据填充
 * 2.模板格式需根据freemarker指定的格式进行设置
 */
@Slf4j
@Service
public class FreeMakerDataFillServiceImpl implements FreeMakerDataFillService {

    private final List<DocumentConvert> convertList;

    @Autowired
    public FreeMakerDataFillServiceImpl(List<DocumentConvert> convertList) {
        this.convertList = convertList;
    }

    @Override
    public byte[] processToByte(File templateFile, Map<String, Object> dataSource) {
        return doProcess(templateFile.getParent(), templateFile.getName(), dataSource);
    }

    @Override
    public byte[] processToByte(String templatePath, Map<String, Object> dataSource) {
        File templateFile = checkTemplateFile(templatePath);
        return doProcess(templateFile.getParent(), templateFile.getName(), dataSource);
    }

    @Override
    public byte[] processToByte(String templateDir, String templateName, Map<String, Object> dataSource) {
        checkTemplateFile(templateDir, templateName);
        return doProcess(templateDir, templateName, dataSource);
    }

    @Override
    public ByteArrayInputStream processToStream(File templateFile, Map<String, Object> dataSource) {
        byte[] outBytes = processToByte(templateFile, dataSource);
        if (outBytes == null || outBytes.length < 1) {return null;}
        //转换为字节流
        return new ByteArrayInputStream(outBytes);
    }

    @Override
    public ByteArrayInputStream processToStream(String templatePath, Map<String, Object> dataSource) {
        byte[] outBytes = processToByte(templatePath, dataSource);
        if (outBytes == null || outBytes.length < 1){ return null;}
        //转换为字节流
        return new ByteArrayInputStream(outBytes);
    }

    @Override
    public ByteArrayInputStream processToStream(String templateDir, String templateName, Map<String, Object> dataSource) {
        byte[] outBytes = processToByte(templateDir, templateName, dataSource);
        if (outBytes == null || outBytes.length < 1) {return null;}
        //转换为字节流
        return new ByteArrayInputStream(outBytes);
    }


    /**
     * 填充数据至模板中
     */
    private byte[] doProcess(String templateDir, String templateName, Map<String, Object> dataSource) {
        DocumentConfiguration fillConfig;
        StringWriter outWriter;
        try {
            log.debug("模板名称:{},填充数据开始,data is {}", templateName, JSONUtil.parse(dataSource));
            //填充数据转换自定义方法
            if (CollUtil.isNotEmpty(convertList)) {
                convertList.forEach(c -> dataSource.put(c.getConvertName(), c));
            }
            //根据模板目录获取对象
            fillConfig = new DocumentConfiguration(templateDir);
            outWriter = new StringWriter();
            //获取模板对象
            Template template = fillConfig.getTemplate(templateName);
            //填充数据至模板中
            template.process(dataSource, outWriter);
            log.info("模板名称:{},填充数据结束...", templateName);
            return outWriter.toString().getBytes(StandardCharsets.UTF_8);
        } catch (Exception e) {
            String msg = String.format("填充模板数据出错, 模板名称:%1s", templateName);

            log.error(msg + ", 出错信息: " + e);
            throw new RuntimeException(msg);
        }
    }


    /**
     * 检查模板路径
     */
    private File checkTemplateFile(String templatePath) {
        if (StringUtils.isBlank(templatePath)) {
            throw new RuntimeException("数据填充模板路径不允许为空");
        }
        File templateFile = new File(templatePath);
        if (!templateFile.exists()) {
            throw new RuntimeException("数据填充模板文件不存在");
        }
        return templateFile;
    }

    /**
     * 检查模板路径
     */
    private File checkTemplateFile(String templateDir, String templateName) {
        if (StringUtils.isBlank(templateDir)) {
            throw new RuntimeException("数据填充模板目录不允许为空");
        }
        if (StringUtils.isBlank(templateName)) {
            throw new RuntimeException("数据填充模板名称不允许为空");
        }
        String templatePath = String.format("%1s%2s%3s", templateDir, File.separator, templateName);
        File templateFile = new File(templatePath);
        if (!templateFile.exists()) {
            throw new RuntimeException("数据填充模板文件不存在");
        }
        return templateFile;
    }
}
